package com.ryan.demo.grpc.server.config;

import com.ryan.demo.grpc.api.SubEventHubGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;

/**
 * @description SubEventHubConfig
 * @Author MRyan
 * @Date 2023/10/7 19:22
 * @Version 1.0
 */
@Configuration(value = "subEventHubConfig")
public class SubEventHubConfig {

    private final ManagedChannel managedChannel;


    public SubEventHubConfig() {
        this.managedChannel = createManagedChannel();
    }

    @Bean(name = "subEventHubManagedChannel")
    public ManagedChannel managedChannel() {
        return managedChannel;
    }

    private ManagedChannel createManagedChannel() {
        return ManagedChannelBuilder.forAddress("localhost", 9090)
                .usePlaintext()
                .build();
    }

    @Bean(name = "subEventHubBlockingStub")
    public SubEventHubGrpc.SubEventHubBlockingStub subEventHubBlockingStub() {
        return SubEventHubGrpc.newBlockingStub(managedChannel);
    }

    @PreDestroy
    public void shutdown() {
        if (!managedChannel.isShutdown()) {
            managedChannel.shutdown();
        }
    }
}
